package tp.pr3.instructions;

import tp.pr3.NavigationModule;
import tp.pr3.RobotEngine;
import tp.pr3.instructions.exceptions.InstructionExecutionException;
import tp.pr3.instructions.exceptions.WrongInstructionFormatException;
import tp.pr3.items.ItemContainer;
import tp.pr3.util.ErrorMessages;
import tp.pr3.util.InstructionParser;
import tp.pr3.util.Messages;

public class ScanInstruction implements Instruction{

	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException {
		String arg = InstructionParser.parseCommand(cad, CmdDic.scanCommand);
		try {
			inputId = InstructionParser.getArg(arg);
			isAll = false;
		} catch (WrongInstructionFormatException ex) {
			isAll = true;
		}
		return this;
	}

	@Override
	public String getHelp() {
		return CmdDic.scanHelp;
	}

	@Override
	public void configureContext(RobotEngine engine, NavigationModule navigation, ItemContainer robotContainer) {
		this.robotEngine = engine;
		this.robotContainer = robotContainer;
	}

	/**
	 * scans an item from the pocket or the whole pocket if the instruction was constructed without an argument
	 */
	@Override
	public void execute() throws InstructionExecutionException {
		if (this.isAll)  { //Caso de escanear todo
			String inventory = this.robotContainer.toString();
			if (inventory.equals("")) this.robotEngine.robotSays(Messages.OUTPUT_SCAN_NONE);
			else {	
				this.robotEngine.robotSays(Messages.OUTPUT_SCAN_ALL);
				System.out.println(inventory);
			}
		}
		else { //Caso de escanear uno solo
			if (this.robotContainer.getItem(inputId) == null)
				throw new InstructionExecutionException(ErrorMessages.IEE_SCAN_FAIL);
			else
				this.robotEngine.robotSays(this.robotContainer.getItem(inputId).toString());
		}
	}
	
	private String inputId;
	private boolean isAll = false; //true if scan has no arguments
	
	private RobotEngine robotEngine;
	private ItemContainer robotContainer;
}
